import * as React from "react";
import { View, Modal } from "react-native";
import Picker from "react-native-picker";

interface Props extends React.Props<any> {
  isPickerVisible: boolean;
  currentPickerValue: string;
  data: Array<any>;
  onConfirm: (pickerString: string) => void;
  onCancel: () => void;
}

export default class MyPicker extends React.Component<Props> {
  constructor(props: Props) {
    super(props);
  }

  render() {
    return (
      <Modal
        visible={this.props.isPickerVisible}
        animationType="fade"
        transparent
        onRequestClose={() => {
          console.warn("modal消失了");
        }}
      >
        <View
          style={{
            flex: 1,
            backgroundColor: "rgba(0,0,0,0.3)"
          }}
        />
      </Modal>
    );
  }

  _showPicker = () => {
    let key = "";
    let value = "";
    if (this.props.currentPickerValue.length > 0) {
      key = this.props.currentPickerValue.split(" - ")[0];
      value = this.props.currentPickerValue.split(" - ")[1];
    } else {
      key = Object.keys(this.props.data[0])[0];
      value = this.props.data[0][key][0];
    }
    Picker.init({
      pickerData: this.props.data,
      selectedValue: [key, value],
      pickerTitleText: "选择器",
      pickerConfirmBtnText: "确定",
      pickerCancelBtnText: "取消",
      pickerBg: [250, 250, 250, 1],
      onPickerConfirm: (data: any) => {
        this.props.onConfirm(`${data[0]} - ${data[1]}`);
      },
      onPickerCancel: this._hidePicker
    });
    Picker.show();
  };

  _hidePicker = () => {
    Picker.hide();
    this.props.onCancel();
  };
}
